<template>
  <div class="menu-wrapper">
    <office-dialog ref="officeDialog" @confirm="dialogConfirm" />
    <el-form ref="shopForm" :model="form" :rules="rules" label-width="120px">
      <div style="display: flex">
        <div>
          <el-form-item label="厨团名称" prop="name">
            <el-input v-model="form.name" style="width: 520px;"/>
          </el-form-item>
          <div style="display: flex">
            <el-form-item label="联系人" prop="linkman">
              <el-input v-model="form.linkman" style="width: 200px;"/>
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
              <el-input v-model="form.telephone" style="width: 200px;"/>
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="注册账号" prop="username">
              <el-input v-model="form.username" style="width: 200px;"/>
            </el-form-item>
            <el-form-item label="登录密码" prop="password">
              <el-input show-password v-model="form.password" style="width: 200px;"/>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="厨师团简介" prop="content">
              <el-input type="textarea" v-model="form.content" ></el-input>
            </el-form-item>
          </div>
             <el-form-item label="分类">
            <el-cascader
              v-model="calssvalue"
              :options="Classification"
              :props="props"
              style="width: 200px"
            >
            </el-cascader>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="厨师团logo" prop="logo">
            <single-upload v-model="form.logo" style="display: inline-block;margin-left: 10px" />
          </el-form-item>
        </div>
      </div>
      <el-tabs>
        <el-tab-pane label="位置信息">
          <el-form-item label="具体位置" prop="lat">
            <el-col :span="12">
              <el-button type="primary" round @click="mapShowFn"><i class="el-icon-map-location" /> 点击选择定位</el-button>
            </el-col>
          </el-form-item>
          <el-form-item label="所在地" prop="areaName">
            <el-col :span="12">
              <Distpicker :province="district.province" :city="district.city" :area="district.area" @selected="onSelected" />
            </el-col>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-col :span="12">
              <el-input v-model="form.address" />
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="银行资料">
          <div style="display: flex">
            <el-form-item label="开户银行" prop="bankId">
              <el-select style="width: 200px;display: inline-block" v-model="form.bankId" placeholder="请选择银行">
                <el-option :label="item.name" :value="item.id" v-for="item in banks"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="账号类型" prop="bankType">
              <el-select style="width: 200px;display: inline-block" v-model="form.bankType" placeholder="请选择账户类型">
                <el-option label="对公账号" :value="0" ></el-option>
                <el-option label="对私账号" :value="1" ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="账号" prop="bankNum">
              <el-input v-model="form.bankNum" style="width: 200px;"/>
            </el-form-item>
            <el-form-item label="开户名" prop="bankName">
              <el-input v-model="form.bankName" style="width: 200px;"/>
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="交易手续费(%)">
              <el-input v-model="form.brokerage" style="width: 200px;"/>
            </el-form-item>
            <el-form-item label="收单手续费(%)">
              <el-input v-model="form.paybill" style="width: 200px;"/>
            </el-form-item>
          </div>
        </el-tab-pane>
        <el-tab-pane label="进件资料">
          <div style="display: flex">
            <el-form-item label="厨师证">
              <single-upload v-model="form.license" style="display: inline-block;margin-left: 10px" />
            </el-form-item>
            <el-form-item label="健康证">
              <single-upload v-model="form.food" style="display: inline-block;margin-left: 10px" />
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="身份证正面">
              <single-upload v-model="form.idCardFront" style="display: inline-block;margin-left: 10px" />
            </el-form-item>
            <el-form-item label="身份证反面">
              <single-upload v-model="form.idCardBack" style="display: inline-block;margin-left: 10px" />
            </el-form-item>
          </div>
<!--          <div style="display: flex">-->
<!--            <el-form-item label="店面门头照">-->
<!--              <single-upload v-model="form.thedoor" style="display: inline-block;margin-left: 10px" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="店内场景照">-->
<!--              <single-upload v-model="form.scene" style="display: inline-block;margin-left: 10px" />-->
<!--            </el-form-item>-->
<!--          </div>-->
        </el-tab-pane>
        <el-tab-pane label="打印设置">
          <el-form-item label="打印机用户">
            <el-col :span="5">
              <el-input v-model="form.printeru" />
            </el-col>
          </el-form-item>
          <el-form-item label="打印机密钥">
            <el-col :span="5">
              <el-input v-model="form.printerp" />
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="配送设置">
          <el-form-item label="配送方式" prop="">
            <el-select
              v-model="bindShopping"
              multiple
              @change="changeDeliverMethod"
              style="width: 200px"
            >
              <el-option label="到点提货" :value="1"></el-option>
              <el-option label="同城配送" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="骑手插件" prop="" v-if="shippingIsShow==true">
            <el-select
              v-model="form.riderPluginId"
              style="width: 200px">
              <el-option label="商家自送" value="shopDeliverPlugin"></el-option>
<!--              <el-option label="达达配送" value="dadaDeliverPlugin"></el-option>-->
            </el-select>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
      <el-form-item>
        <el-button type="primary" :loading="clicked" @click="saveshop('shopForm')">&nbsp&nbsp完 成&nbsp&nbsp</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      title="请选择具体位置"
      :visible.sync="mapShow"
      top="5vh"
      width="800px"
      :before-close="handleClose"
    >
      <Map :initcenter="[form.lng, form.lat]" @getMap="getMap" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapShow = false">取 消</el-button>
        <el-button type="primary" @click="savelngLat">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style scoped>
  /deep/ .el-upload--picture-card {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
    text-align: center;
  }
  /deep/.el-upload-list--picture {
    /*position: absolute;*/
    width: 110px;
  }
  /deep/.el-upload__tip{}
  .menu-wrapper{
    margin: 15px;
  }
</style>
<script>
  import { list as classlist } from "@/api/shopCategory";
  import singleUpload from '@/components/Upload/singleUpload'
  import {list as bankList} from '@/api/bank'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import { EventBus } from '@/api/eventBus'
  import utils from '../../utils/utils.js'
  import OfficeDialog from '@/components/OfficeDialog'
  import { saveMchShop } from '@/api/shop'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import Map from '@/components/GaodeMap/index'
  import { list as sysEmployeeList } from '@/api/sysEmployee'
  import { checkUserExists } from '@/api/sysUser'
  import md5 from 'js-md5'
  export default {
    name: 'famousCooker-add',
    directives: { permission },
    filters: {

    },
    components: {
      OfficeDialog,
      Distpicker,
      singleUpload,
      Map
    },
    data() {
      const checkUser = (rule, value, callback) => { //检查账号是否存在
        if (utils.isNull(value)) {
          callback(new Error('请输入注册账号'))
        } else {
          const params = new URLSearchParams();
          params.append('username',value)
          checkUserExists(params).then(response => {
            console.log(response)
            if ( response.data !== 0) {
              callback(new Error('该账号已存在，不能重复'))
            } else {
              callback()
            }
          })
        }
      }
      const checkPassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码长度不能小于6位'))
        } else {
          callback()
        }
      }
      return {
          calssvalue:[],
      props: {
        value: "id",
        label: "name",
        children: "childrens",
      },
      Classification: [], //分类列表
        banks:[],
        tempLng: '',
        tempLat: '',
        password:'',
        userName:'',
        shippingIsShow:false,
        bindShopping:[],
        mapShow: false,
        district: {},
        clicked: false, // 按钮防双击
        topName: '',
        typeOneDisabled: false, // 公司类型是否禁用
        typeTwoDisabled: false, // 部门类型是否禁用
        memberOptions: [],
        form: {
           shopCategoryId:'',
          name: '',
          scopeType:3,
          linkman: '',
          riderPluginId:'',
          telephone: '',
          food:'',
          content:'',
          logo:'',
          deliverMethod:'',
          bankType:0,
          password:'',
          username:'',
          bankId:'',
          idCardFront:'',
          thedoor:'',
          idCardBack:'',
          bankNum:'',
          bankName:'',
          scene:'',
          status: 0,
          brokerage:0,
          license:'',
          paybill:0,
          type: 0,
          modifyDate: '',
          address: '', // 地址
          lng: '', // 经度
          lat: '', // 纬度
          areaName: '',
          printeru: '',
          printerp: '',
          managerId: ''
        },
        rules: {
          name: [
            { required: true, message: '请输入商户名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
          username: [
            { required: true, validator: checkUser, trigger: 'blur' }
          ],
          password: [
            { required: true,  validator: checkPassword, trigger: 'blur' }
          ],
          bankId:[{required:true,message:'请选择开户银行'}],
          bankNum:[{required:true,message:'请输入银行账号'}],
          bankName:[{required:true,message:'请输入开户名'}],
          officeId: [
            { required: true, message: '请选择所属部门' }
          ],
          linkman: [
            { required: true, message: '请输入联系人', trigger: 'blur' }
          ],
          telephone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' }
          ],
          areaName: [
            { required: true, message: '请选择仓库所在地址' }
          ],
          address: [
            { required: true, message: '请选择仓库详细地址' }
          ],
          lat: [
            { required: true, message: '请选择仓库具体坐标' }
          ],
          type: [
            { required: true, message: '请选择类型', trigger: 'blur' }
          ],
          managerId: [
            { required: true, message: '请选择店长', trigger: 'blur' }
          ],
           logo: [{ required: true, message: "请选择厨师团logo", trigger: "blur" }],
        }
      }
    },
    created() {

      this.queryMember('')
      this.loadBank()
      this.getclassification()
    },
    methods: {
      changeDeliverMethod(val){
        if (val.length>0&&val.length<2){
          this.form.deliverMethod=val[0]
          if (val[0]==2){
            this.shippingIsShow=true
          }else{
            this.shippingIsShow=false
          }
        }else if (val.length>1){
          this.form.deliverMethod=val[0]+''+val[1]
          this.shippingIsShow=true
        }else{
          this.shippingIsShow=false
        }
      },
       getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].childrens.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].childrens = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].childrens);
        }
      }
      return data;
    },
    //获取分类列表
    getclassification() {
      let params = new URLSearchParams();
      params.append("scopeType", this.form.scopeType);
      classlist(params).then((res) => {
        this.Classification = this.getTreeData(res.data);
        console.log(res);
      });
    },
      loadBank(){
        bankList().then(res=>{
          this.banks=res.data.data
        })
      },
      queryMember(query) {
        clearTimeout(this.memberMark)
        this.memberMark = setTimeout(() => {
          this.memberOptions = []
          sysEmployeeList({ employeeType:0,name: query }).then(res => {
            this.memberOptions = res.data.data
          }).catch(err => { console.log(err) })
        }, 300)
      },
      typeChange(e) {
        if (e !== 0) {
          this.form.managerId = ''
        }
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      },
      mapShowFn() {
        this.mapShow = !this.mapShow
      },
      getMap(lng, lat,address) {
        console.log(lng, lat)
        // 定义变量保存经纬度
        console.log(address)
        this.form.address=address.formattedAddress
        this.district.province = address.addressComponent.province
        this.district.city = address.addressComponent.city
        this.district.area = address.addressComponent.district
        this.form.areaId=address.addressComponent.adcode
        this.tempLng = lng
        this.tempLat = lat
      },
      savelngLat() {
        this.form.lng = this.tempLng
        this.form.lat = this.tempLat
        this.mapShow = false
      },
      onSelected(val) {
        console.log(val)
        if (!utils.isNull(val.city) && !utils.isNull(val.area) && !utils.isNull(val.area.code)) {
          this.form.areaId = val.area.code
          this.form.areaName = val.province.value + val.city.value + val.area.value
          // this.form.areaName = val.area.value
        }
      },
      dialogShow() {
        console.log('点击了')
        this.$refs.officeDialog.show()
      },
      dialogConfirm(val) {
        this.form.officeId = val.id
        this.topName = val.name
        /* if (val.type == 0) {
          this.form.type = 1
          this.typeOneDisabled = false
          this.typeTwoDisabled = false
        } else {
          this.form.type = 1
          this.typeOneDisabled = true
        } */
      },
      saveshop(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            _this.clicked = true
            const date = new Date()
            this.form.modifyDate = date
            this.userName=_this.form.username
            this.password=_this.form.password
            const params = new URLSearchParams();
            params.append('username', this.userName)
            params.append('password', md5(_this.password))
            delete this.form.username
            delete this.form.password
             this.form.shopCategoryId = this.calssvalue[this.calssvalue.length - 1];
            saveMchShop(_this.form,params).then(response => {
              _this.clicked = false
              EventBus.$emit('famousCooker-add', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({ visitedViews }) => {
                _this.$router.push({
                  path: '/famousCooker/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  }
</script>
